package jhunter.dao.condition;

import java.util.ArrayList;
import java.util.List;

import jhunter.dao.EntityExt;
import jhunter.dao.bo.BaseObject;
import jhunter.dao.type.TypeHandlerFactory;

public class ExampleCondition implements Condition {

	private EntityExt entity;
	private BaseObject example;
	private String relation;

	public ExampleCondition() {
	
	}
	
	public ExampleCondition(EntityExt entity, BaseObject example) {
		this(entity, example, "and");
	}

	public ExampleCondition(EntityExt entity, BaseObject example, String relation) {
		super();
		this.entity = entity;
		this.example = example;
		this.relation = relation;
	}

	@Override
	public String getWhereSql() {
		StringBuilder sb = new StringBuilder();
		if (example != null) {
			List<String> propSql = new ArrayList<String>();
			for (int i = 0; i < entity.getProperties().size(); i++) {
				String p = entity.getProperties().get(i);
				if (example.containsKey(p)) {
					Object object = example.get(p);
					if (object == null) {
						propSql.add(entity.getTableAlias() + "." + entity.getColumnName(p) + " is null ");
					} else {
						propSql.add(entity.getTableAlias() + "." + entity.getColumnName(p) + " = ? ");
					}
				}
			}
			for (int i = 0; i < propSql.size(); i++) {
				String sql = propSql.get(i);
				if (i != 0) {
					sb.append(" ").append(relation).append(" ");
				}
				sb.append(sql);
			}
		}
		return sb.toString();
	}

	@Override
	public List<Object> getParameters() {
		List<Object> params = new ArrayList<Object>();
		if (example != null) {
			for (int i = 0; i < entity.getProperties().size(); i++) {
				String p = entity.getProperties().get(i);
				if (example.containsKey(p)) {
					Object object = example.get(p);
					if (object == null) {

					} else {
						String type = entity.getPropsMap().get(p).getType();
						params.add(TypeHandlerFactory.getTypeHandler(type).getSqlObject(object));
					}
				}
			}
		}
		return params;
	}

	@Override
	public boolean isEmpty() {

		return example == null || example.isEmpty();
	}

	public EntityExt getEntity() {
		return entity;
	}

	public void setEntity(EntityExt entity) {
		this.entity = entity;
	}

	public BaseObject getExample() {
		return example;
	}

	public void setExample(BaseObject example) {
		this.example = example;
	}

	public String getRelation() {
		return relation;
	}

	public void setRelation(String relation) {
		this.relation = relation;
	}

}
